package com.zhu.spider;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.model.HttpRequestBody;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.utils.HttpConstant;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000)
            .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");

    public Main(int pageCount) {
        this.pageCount = pageCount;
    }

    public Main() {
    }

    public static final String URL_LIST = "http://www.hgsj.com/industry/50.html";

    public static int pageNum = 50;

    public static List<String> detailUrl = new ArrayList<>();
    public static List<String> contentList = new ArrayList<>();
    public int pageCount;
    public void process(Page page) {

        int number = Integer.parseInt(getUrlNumber(page.getUrl().toString()));
        if (number < 100){
            Main.detailUrl.addAll(page.getHtml().xpath("//*[@width=\"85%\"]/a/@href").all());

            List<String> list = new ArrayList<>();
            for (int i = 2; i < 50; i++) {
                list.add("http://www.hgsj.com/industry/"+number+"_"+i+".html");
            }
            page.addTargetRequests(list);
        }else if (number < 20000){
            Main.detailUrl.addAll(page.getHtml().xpath("//*[@width=\"85%\"]/a/@href").all());
        }else {
            contentList.addAll(page.getHtml().xpath("//*[@class=\"article\"]").all());
//            System.out.println(page.getHtml().xpath("//*[@class=\"article\"]/p").all());
        }

    }


    public static String[] getAllTotalPage(){
        String[] strings = new String[50];
        for (int i = 0; i < 50; i++) {
            strings[i] = "http://www.hgsj.com/industry/"+(i+50)+".html";
        }
        return strings;
    }

    public String getUrlNumber(String url){
        StringBuilder s = new StringBuilder();
        for (char c:url.toCharArray()) {
            if (c>=48 && c<=57){
                s.append(c);
            }
        }
        return s.toString();
    }


    public Site getSite() {
        return site;
    }

    public static void main(String[] args) throws InterruptedException, IOException {

        Spider.create(new Main()).addUrl(getAllTotalPage()).thread(20).run();
        System.out.println(detailUrl);
        String[] arr = new String[detailUrl.size()];
        for (int i = 0; i < detailUrl.size(); i++) {
            arr[i] = "http://www.hgsj.com"+detailUrl.get(i);
        }
        Spider.create(new Main(20)).addUrl(arr).thread(20).run();


        outToExcel();

    }

    static void outToExcel() throws IOException {

//书写正则表达式
        ExcelExportInterface excelExport = new ExcelExport("D:\\export.xls");
        //8位海关编码
        for (String s:contentList){
        List<String> list = new ArrayList<>(9);
        list.add(getString(s,"中国8位海关编码：","&nbsp;"));
        list.add(getString(s,"产品名称：","&nbsp;"));
        list.add(getString(s,"产品英文名称： ","<br>"));
        list.add(getString(s,"2015年中国出口总数量：","&nbsp;"));
        list.add(getString(s,"2015年中国出口总金额（美元）：&nbsp;","&nbsp;"));
        list.add(getString(s,"2015年中国出口平均单价：&nbsp;","&nbsp;"));
        list.add(getString(s,"中国部分出口商： ","<br>"));
        list.add(getString(s,"国外部分进口商： ","<br>"));
        list.add(getString(s,"国外部分出口商： ","<br>"));

        String[] arr = new String[9];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }
        excelExport.setRowContent(arr);
        }
        excelExport.exportContent();
    }

    static String getString(String s,String startStr,String endStr){
        try {
            int start = s.indexOf(startStr);
            int end = s.indexOf(endStr,start+startStr.length());
//            System.out.println(s.substring(start+startStr.length(),end));
            String strr = s.substring(start+startStr.length(),end);
            strr = strr.replace("&amp;",",");
            return strr;
        }catch (Exception e){

        }
        return "";

    }


}
